﻿using System;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
using Core.AdminGroupMenuPermission;
using Core.Authenticated;
using Core.Library;
using DataObject;
using DataObject.Cache;
using DataObject.Members;

namespace CMS.Controls.Members
{
    public partial class MembersManager : AuthenticatedControl
    {
        #region Variables

        protected string Tab;
        protected string KName;
        protected string KEmail;
        protected string Url;
        protected int PageIndex;
        protected int PageSize;
        protected int WaitingForPublish;
        protected int Publish;
        protected int Removed;
        protected int Round1;
        protected int Round2;
        protected int Round3;

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            Tab = Utils.GetIdFromRequestString(Utils.Tab, string.Empty);

            if (string.IsNullOrEmpty(Tab))
                Response.Redirect(UrlHelpers.ListTab(cControl.AdminMenuId, MemberRound.Round1.ToString()));

            KName = Utils.GetIdFromRequestString(Utils.KName, string.Empty);
            KEmail = Utils.GetIdFromRequestString(Utils.KEmail, string.Empty);
            PageIndex = Utils.GetIdFromRequestString(Utils.PageIndex, SettingValues.PageIndex);
            PageSize = Utils.GetIdFromRequestString(Utils.PageSize, ConvertUtility.ConvertTo<int>(ddlPageSize.SelectedValue));
            Url = HttpUtility.UrlEncode(Request.Url.ToString());

            if (!IsPostBack)
            {
                InitArticle();
                ListData();
                GetStatistics();
            }
        }

        #region Statistics

        private void GetStatistics()
        {
            WaitingForPublish = MembersController.Members_GetStatistic((int)MemberRound.NoRound, (int)MemberStatus.IsWaitingForPublish);
            Publish = MembersController.Members_GetStatistic((int)MemberRound.NoRound, (int)MemberStatus.IsPublished);
            Removed = MembersController.Members_GetStatistic((int)MemberRound.NoRound, (int)MemberStatus.IsRemoved);
            Round1 = MembersController.Members_GetStatistic((int)MemberRound.Round1, (int)MemberStatus.IsPublished);
            Round2 = MembersController.Members_GetStatistic((int)MemberRound.Round2, (int)MemberStatus.IsPublished);
            Round3 = MembersController.Members_GetStatistic((int)MemberRound.Round3, (int)MemberStatus.IsPublished);
        }

        #endregion

        #region Bind Data

        private void InitArticle()
        {
            var isShowPublished = false;

            var adminGroupMenuPermission =
                    AdminGroupMenuPermissionController.AdminGroupMenuPermission_GetBy_AdminUserId_AdminMenuId(CurrentUser.AdminUserId, cControl.AdminMenuId);
            if (adminGroupMenuPermission.Count > 0)
            {
                foreach (var agmp in adminGroupMenuPermission)
                {
                    isShowPublished = StatusHelper.IsChecked(agmp.Status, (int)PermissionObject.CanPublish);
                }
            }

            hfTab.Value = Tab;
            if (!string.IsNullOrEmpty(hfTab.Value))
            {
                switch (hfTab.Value)
                {
                    case "IsRemoved":
                        hfStatus.Value = ((int)MemberStatus.IsRemoved).ToString();
                        hfRound.Value = ((int)MemberRound.NoRound).ToString();
                        btnDelete.Visible = false;
                        btnRestore.Visible = isShowPublished;
                        break;
                    case "IsWaitingForPublish":
                        hfStatus.Value = ((int)MemberStatus.IsWaitingForPublish).ToString();
                        hfRound.Value = ((int)MemberRound.NoRound).ToString();
                        btnRemove.Visible = isShowPublished;
                        btnPublish.Visible = isShowPublished;
                        break;
                    case "IsPublished":
                        hfStatus.Value = ((int)MemberStatus.IsPublished).ToString();
                        hfRound.Value = ((int)MemberRound.NoRound).ToString();
                        btnRemove.Visible = isShowPublished;
                        btnRound1.Visible = isShowPublished;
                        break;
                    case "Round1":
                        hfStatus.Value = ((int)MemberStatus.IsPublished).ToString();
                        hfRound.Value = ((int)MemberRound.Round1).ToString();
                        btnRemove.Visible = isShowPublished;
                        btnRound2.Visible = isShowPublished;
                        break;
                    case "Round2":
                        hfStatus.Value = ((int)MemberStatus.IsPublished).ToString();
                        hfRound.Value = ((int)MemberRound.Round2).ToString();
                        btnRemove.Visible = isShowPublished;
                        btnRound3.Visible = isShowPublished;
                        break;
                    case "Round3":
                        hfStatus.Value = ((int)MemberStatus.IsPublished).ToString();
                        hfRound.Value = ((int)MemberRound.Round3).ToString();
                        btnRemove.Visible = isShowPublished;
                        break;
                }
            }
            else
            {
                ltMessage.Text = MessageUtility.ShowMessage(string.Empty, "Không lấy được dữ liệu.", MessageType.Failure);
            }
        }

        private void ListData()
        {
            var currentKName = UnicodeUtility.DecodeFrom64(KName);
            if (currentKName.IndexOf("Tên đầy đủ") != -1)
                currentKName = string.Empty;
            var currentKEmail = UnicodeUtility.DecodeFrom64(KEmail);
            if (currentKEmail.IndexOf("Email") != -1)
                currentKEmail = string.Empty;

            lvList.DataSource = MembersController.Members_GetListByTypeByStatusPaging(currentKName,currentKEmail,
                                                                                ConvertUtility.ConvertTo<int>(hfRound.Value),
                                                                                ConvertUtility.ConvertTo<int>(hfStatus.Value),
                                                                                PageIndex, PageSize, string.Format("{0} DESC, {1} DESC, {2} DESC", Constants.Table_Members.Member_HomePageFocus, Constants.Table_Members.isCheatVote, Constants.Table_Members.Member_ID));
            lvList.DataBind();

            var totalRecords = MembersController.Members_Count(currentKName,currentKEmail,
                                                                                ConvertUtility.ConvertTo<int>(hfRound.Value),
                                                                                ConvertUtility.ConvertTo<int>(hfStatus.Value));
            
            txtKName.Value = currentKName;
            txtKEmail.Value = currentKEmail;
            ddlPageSize.SelectedValue = PageSize.ToString();
            ltPager.Text = PagerUtility.PageLinks(PageIndex, PageSize, totalRecords, 5,
                                UrlHelpers.ListSearch(cControl.AdminMenuId, currentKName, currentKEmail, hfTab.Value, "{0}", PageSize));

        }

        protected void lvList_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            if (e.Item.ItemType == ListViewItemType.DataItem)
            {
                var round = ConvertUtility.ConvertTo<int>(hfRound.Value);
                switch (round)
                {
                    case 1:
                        e.Item.FindControl("phVote1").Visible = true;
                        break;
                    case 2:
                        e.Item.FindControl("phVote2").Visible = true;
                        break;
                    case 3:
                        e.Item.FindControl("phVote3").Visible = true;
                        break;
                }

                var ltImage = (Literal)e.Item.FindControl("ltImage");
                var status = ConvertUtility.ConvertTo<bool>(((HiddenField)e.Item.FindControl("hfIsHomePage")).Value);
                var id = ConvertUtility.ConvertTo<int>(((HiddenField)e.Item.FindControl("hfMemberId")).Value);

                var imgIcon = "<img mid=\"" + id + "\" ishomepage=\"" + status + "\" src=\"/images/icons/color/user-black-female.png\" class=\"floatleft mr5 topDir btn14\" title=\"Bình thường\" onclick=\"memberToggleIsHomePage(this);\" alt=\"\"/>";

                if (status)
                    imgIcon = "<img mid=\"" + id + "\" ishomepage=\"" + status + "\" src=\"/images/icons/color/pin.png\" class=\"floatleft mr5 topDir btn14\" title=\"Nổi bật trang chủ\" onclick=\"memberToggleIsHomePage(this);\" alt=\"\"/>";

                ltImage.Text = imgIcon;

                var ltIsSlide = (Literal)e.Item.FindControl("ltIsSlide");
                var isSlide = ConvertUtility.ConvertTo<bool>(((HiddenField)e.Item.FindControl("hfIsSlide")).Value);
                imgIcon = "<img mid=\"" + id + "\" isslide=\"" + isSlide + "\" src=\"/images/icons/color/user-black-female.png\" class=\"floatleft mr5 topDir btn14\" title=\"Bình thường\" onclick=\"memberToggleIsSlide(this);\" alt=\"\"/>";

                if (isSlide)
                    imgIcon = "<img mid=\"" + id + "\" isslide=\"" + isSlide + "\" src=\"/images/icons/color/pin.png\" class=\"floatleft mr5 topDir btn14\" title=\"Hiển thị trên slide\" onclick=\"memberToggleIsSlide(this);\" alt=\"\"/>";

                ltIsSlide.Text = imgIcon;
            }
        }

        #endregion

        #region Action

        private void UpdateStatus(int status, int round)
        {
            ltMessage.Text = string.Empty;
            var count = 0;
            foreach (ListViewDataItem lvi in lvList.Items)
            {
                var cbItem = (CheckBox)lvi.FindControl("cbItem");
                if (cbItem == null || !cbItem.Checked) continue;

                count++;
                var id = ConvertUtility.ConvertTo<int>(lvList.DataKeys[lvi.DisplayIndex].Value);
                if (id > 0)
                    MembersController.Members_Update_Status(id, status, round);
            }

            if (count == 0)
                ltMessage.Text = MessageUtility.ShowMessage(string.Empty, "Bạn chưa chọn bài viết nào.", MessageType.Warning);
            else CacheController.RemoveCachePort(Constants.ManagerCacheGroup.User);

            ListData();
            GetStatistics();
        }

        protected void BtnRound3(object sender, EventArgs e)
        {
            UpdateStatus((int)MemberStatus.IsPublished, (int)MemberRound.Round3);
        }

        protected void BtnRound2(object sender, EventArgs e)
        {
            UpdateStatus((int)MemberStatus.IsPublished, (int)MemberRound.Round2);
        }

        protected void BtnRound1(object sender, EventArgs e)
        {
            UpdateStatus((int)MemberStatus.IsPublished, (int)MemberRound.Round1);
        }

        protected void BtnPublish(object sender, EventArgs e)
        {
            UpdateStatus((int)MemberStatus.IsPublished, (int)MemberRound.NoRound);
        }


        protected void BtnRestore(object sender, EventArgs e)
        {
            UpdateStatus((int)MemberStatus.IsWaitingForPublish, (int)MemberRound.NoRound);
        }

        protected void BtnRemove(object sender, EventArgs e)
        {
            UpdateStatus((int)MemberStatus.IsRemoved, (int)MemberRound.NoRound);
        }

        protected void BtnDelete(object sender, EventArgs e)
        {
            UpdateStatus((int)MemberStatus.IsDeleted, (int)MemberRound.NoRound);
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            RedirectLink(PageSize);
        }

        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            RedirectLink(ConvertUtility.ConvertTo<int>(ddlPageSize.SelectedValue));
        }

        public void RedirectLink(int currentPageSize)
        {

            var kName = txtKName.Value.IndexOf("Tên đầy đủ") != -1 ? string.Empty : txtKName.Value;
            var kEmail = txtKEmail.Value.IndexOf("Email") != -1 ? string.Empty : txtKEmail.Value;

            Response.Redirect(UrlHelpers.ListSearch(cControl.AdminMenuId,
                                                        UnicodeUtility.EncodeTo64UTF8(kName),
                                                        UnicodeUtility.EncodeTo64UTF8(kEmail),
                                                        hfTab.Value,
                                                        SettingValues.PageIndex.ToString(), currentPageSize));
        }

        #endregion
    }
}